package code.whmmm.util.spring.quartz;

import code.whmmm.util.spring.quartz.util.QuartzUtil;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * quartz 默认定时器 <br/>
 * 创建时间: 2019年8月14日 13:36:53
 *
 * @author Zero
 */
@Component
public class PersZeroQuartzSchedule {

    private Scheduler scheduler;
    private static final Logger log = LoggerFactory.getLogger(PersZeroQuartzSchedule.class);

    @Autowired
    private void setJobFactory(QuartzJobFactory jobFactory) {
        try {
            this.scheduler.setJobFactory(jobFactory);
        } catch (SchedulerException e) {
            log.error(e.getMessage(), e);
        }
    }

    public PersZeroQuartzSchedule() {
        try {

            this.scheduler = new StdSchedulerFactory().getScheduler();
            //this.scheduler = std;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.error("初始化 pers-zero-scheduler 定时任务 bean 失败!");
        }
    }

    public void startJob(QuartzJob job) {
        if (!job.isEnable()) {
            return;
        }
        String name = job.getClass().getSimpleName();

        String jobName = name + "Job";
        String jobGroup = "defaultJobGroup";

        CronTrigger trigger = QuartzUtil.createCronTrigger(
                job.cron(), name + "Trigger", "defaultTriggerGroup",
                jobName, jobGroup
        );
        JobDetail jobDetail = QuartzUtil.createJobDetail(job.getClass(), jobName, jobGroup);
        try {
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * spring 销毁时，要停止 quartz。
     */
    @PreDestroy
    private void shutdown() {
        try {
            scheduler.shutdown();
            log.info("default-quartz-schedule 已停止..");
        } catch (SchedulerException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * @return {@link Scheduler}
     */
    public Scheduler getScheduler() {
        // 暂停 scheduler.standby();
        // 恢复执行 scheduler.resumeAll();
        return scheduler;
    }


}
